package com.crm.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.crm.base.BaseServiceImpl;
import com.crm.domain.dto.LoginDTO;
import com.crm.domain.entity.Module;
import com.crm.domain.entity.User;
import com.crm.domain.entity.UserRole;
import com.crm.exception.CustomException;
import com.crm.mapper.UserMapper;
import com.crm.result.ResultEnum;
import com.crm.service.ModuleService;
import com.crm.service.UserRoleService;
import com.crm.service.UserService;
import com.crm.utils.SecurityHolderUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户业务层实现类
 */

@Service
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private ModuleService moduleService;

    @Override
    public Boolean add(User user) {

        // 添加用户
        baseMapper.insert(user);

        if (user.getRoleIds() != null) {
            // 添加用户角色
            saveUserRole(user.getId(), user.getRoleIds());
        }

        return true;
    }

    @Override
    public Boolean upd(User user) {
        // 角色ID不为空删除更新用户角色
        if (user.getRoleIds() != null) {
            // 删除用户角色
            userRoleService.deleteByUserId(user.getId());

            // 添加用户角色
            saveUserRole(user.getId(), user.getRoleIds());
        }

        // 修改用户
        return baseMapper.update(user) > 0;
    }

    private void saveUserRole(Integer userId, List<Integer> roleIds) {
        // 添加用户角色角色
        UserRole userRole = new UserRole(null, userId, roleIds);
        userRoleService.add(userRole);
    }

    @Override
    public void login(LoginDTO loginDTO, HttpSession session, HttpServletResponse response) throws Exception {
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        Boolean isRemPwd = loginDTO.getIsRemPwd();
        String code = loginDTO.getCode();

        // 判断用户名或密码是否为空
        if (ObjectUtils.isEmpty(username) || ObjectUtils.isEmpty(password)) {
            throw new CustomException(ResultEnum.USERNAME_OR_PASSWORD_NULL);
        }

        // 判断验证码是否为空
        if(ObjectUtils.isEmpty(code)){
            throw new CustomException(ResultEnum.CODE_NULL);
        }

        // 判断验证码是否正确
        String localCode = (String)session.getAttribute("code");
        if(!code.equals(localCode)){
            throw new CustomException(ResultEnum.CODE_ERROR);
        }

        // 判断用户是否存在
        User user = baseMapper.findName(username);
        if (ObjectUtil.isNull(user)) {
            throw new CustomException(ResultEnum.USERNAME_NOT_EXIST);
        }

        // 判断密码是否加密
        String digestPwd = password;
        if (NumberUtil.isNumber(password)) {
            digestPwd = DigestUtil.md5Hex(password);
        }

        // 判断密码是否正确
        if (!user.getPassword().equals(digestPwd)) {
            throw new CustomException(ResultEnum.PASSWORD_ERROR);
        }

        // 是否要记住密码
        if (isRemPwd) {
            // 设置保存用户名的 cookie
            Cookie cookieUserName = new Cookie("username", URLEncoder.encode(username, "UTF-8"));
            cookieUserName.setMaxAge(60 * 60 * 24 * 7); //  cookie 保存一个星期
            response.addCookie(cookieUserName);

            // 设置保存密码的 cookie
            Cookie cookiePassword = new Cookie("password", URLEncoder.encode(password, "UTF-8"));
            cookiePassword.setMaxAge(60 * 60 * 24 * 7); //  cookie 保存一个星期
            response.addCookie(cookiePassword);

            // 设置保存记住密码的 cookie
            Cookie cookieIsRemPwd = new Cookie("isRemPwd", URLEncoder.encode("true", "UTF-8"));
            cookieIsRemPwd.setMaxAge(60 * 60 * 24 * 7); //  cookie 保存一个星期
            response.addCookie(cookieIsRemPwd);
        } else {

            // 如果不需要记住密码则删除cookie
            delCookie(response);
        }

        // 查询用户权限
        List<Module> list = moduleService.findModuleByUid(user.getId(), "");
        List<String> perms = list.stream().map(Module::getModuleUrl).collect(Collectors.toList());
        user.setPerms(perms);

        // 将当前登录的用户保存到 session 中
        session.setAttribute("session_user", user);

        // 登录成功后，将总条数设置为 0
        ServletContext servletContext = session.getServletContext();
        servletContext.setAttribute("total", 0);
    }

    @Override
    public void logout(HttpSession session, HttpServletResponse response) {
        // 删除cookie
        delCookie(response);

        // 销毁session
        session.invalidate();
    }


    @Override
    public Boolean updPwd(String oldPwd, String newPwd) throws Exception {
        User user = SecurityHolderUtil.getUser();

        // 判断用户是否存在
        if (ObjectUtil.isNull(user)) {
            return false;
        }

        // 判断旧密码是否正确
        if (!DigestUtil.md5Hex(oldPwd).equals(user.getPassword())) {
            throw new CustomException(ResultEnum.OLD_PASSWORD_ERROR);
        }

        // 修改密码
        return baseMapper.updateUsersPwd(DigestUtil.md5Hex(newPwd), user.getId()) > 0;

    }

    @Override
    public List<User> findCustomer() {
        return baseMapper.findCustomer();
    }

    @Override
    public List<User> findCreateSaleChance() {
        return baseMapper.findCreateSaleChance();
    }

    @Override
    public Boolean resetPwd(Integer uId) {
        return baseMapper.updateUsersPwd(DigestUtil.md5Hex("123456"), uId) > 0;
    }


    // 删除cookie
    public static void delCookie(HttpServletResponse response) {
        // 清空cookie
        Cookie cookieUserName = new Cookie("username", null);
        cookieUserName.setMaxAge(0); //  删除 cookie
        response.addCookie(cookieUserName);

        Cookie cookiePassword = new Cookie("password", null);
        cookiePassword.setMaxAge(0); //  删除 cookie
        response.addCookie(cookiePassword);

        Cookie cookieIsRemPwd = new Cookie("isRemPwd", "false");
        cookieIsRemPwd.setMaxAge(0); //  删除 cookie
        response.addCookie(cookieIsRemPwd);
    }
}

